﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.Text;

public partial class Account_UserLogin : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void lnkLogin_Click(object sender, EventArgs e)
    {
        Sharemp3DataContext db = new Sharemp3DataContext();
        string username = txtUsername.Text;
        string pass = txtPass.Text;
        string passHash = GetMd5Hash(MD5.Create(), pass);
        try
        {
            UserLogin user = db.UserLogins.Where(i => i.Username == username && i.Password == passHash && i.Role == 2).First<UserLogin>();
            Session["User"] = user;
            Response.Redirect("~/Profile.aspx");
        }
        catch
        {
            lblResult.Text = "Username or password is invalid !";
        }
    }

    private string GetMd5Hash(MD5 md5Hash, string input)
    {
        byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
        StringBuilder sbuilder = new StringBuilder();
        for (int i = 0; i < data.Length; i++)
        {
            sbuilder.Append(data[i].ToString("x2"));
        }
        return sbuilder.ToString();
    } 
}